import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/'
import Layout from '@/views/Layout'
import Pay from '@/views/Pay'
import Search from '@/views/Search'
import searchList from '@/views/Search/searchList.vue'
import Home from '@/views/Layout/home.vue'
import Category from '@/views/Layout/category.vue'
import Cart from '@/views/Layout/cart.vue'
import User from '@/views/Layout/user.vue'
import store from '@/store'
import ProductDetails from '@/views/Details/productDetails.vue'
import Address from '@/views/Address'

Vue.use(VueRouter)

const routes = [{
  path: '/login',
  component: Login
},
{
  path: '/',
  redirect: '/home',
  component: Layout,
  children: [{
    path: '/home',
    component: Home
  },
  {
    path: '/category',
    component: Category
  },
  {
    path: '/cart',
    component: Cart
  },
  {
    path: '/user',
    component: User
  },
  ]
},
{
  path: '/pay',
  component: Pay
},
{
  path: '/search/',
  component: Search
},
{
  path: '/searchlist',
  component: searchList
},
{
  path: '/productDetails',
  component: ProductDetails
},
{
  path: '/address',
  component: Address
},
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 需要登陆权限访问的页面数组 '
const URlARR = ['/pay', '/cart']
//设置全局前置路由守卫,重定向路由页面
router.beforeEach((to, from, next) => {
  const token = store.state.user.userInfo.token;
  const islogin = store.state.user.userInfo.islogin;

  //判断是否为登陆状态,无登陆状态跳转到登陆页面
  //不需要登陆的界面直接放行
  if (!URlARR.includes(to.path)) {
    console.log('1111')
    next()
    return
  }
  //已登陆有token放行
  if (token) {
    console.log('2222')
    next()
    return
  }
  //未登陆,没有token跳转到登陆页面
  if (!islogin) {
    console.log('3333')
    next('/login')
    return
  }
  // 没有 token，但已登录（极少见，补全）
  next('/login')
}


)

export default router